<?php
namespace Qgs\Model;

use \Think\Db;
use Think\Model;

class B2cOrdersModel extends Model
{


    /**
     * 订单列表
     * pay_status 支付状态
     *  0 => app::get('b2c')->_('未支付'),
     * 1 => app::get('b2c')->_('已支付'),
     * 2 => app::get('b2c')->_('已付款至到担保方'), over
     * 3 => app::get('b2c')->_('部分付款'),    over
     * 4 => app::get('b2c')->_('部分退款'),
     * 5 => app::get('b2c')->_('全额退款'),
     *
     * ship_status 发货状态
     * 0 => app::get('b2c')->_('未发货'),
     * 1 => app::get('b2c')->_('已发货'),
     * 2 => app::get('b2c')->_('部分发货'),
     * 3 => app::get('b2c')->_('部分退货'),
     * 4 => app::get('b2c')->_('已退货'),
     *
     * received_status 收货状态
     * 0 => app::get('b2c')->_('未收货'),
     * 1 => app::get('b2c')->_('已收货'),
     *
     * 订单状态 status
     *
     * 'active' => app::get('b2c')->_('活动订单'),
     * 'dead' => app::get('b2c')->_('已作废'),
     * 'finish' => app::get('b2c')->_('已完成'),
     *
     * is_delivery 是否需要发货
     * Y => app::get('b2c')->_('是否需要发货'),
     * N => app::get('b2c')->_('是否需要发货'),
     *
     * pre_delivery_time 预约自提时间
     *
     * pickedup_bn   自提单号
     *
     * mark_text  操作员订单备注
     *
     *
     * shipping_id  配送方式（table:dlytype）
     *
     *
     */
    public function orderList($p, $view)
    {


        $sub = array(
            0 => array('o.pay_status' => '1', 'o.ship_status' => array('in', array('0', '2')), 'o.status' => 'active', 'o.local_id' => session('userInfo.local_id')),// 待发货
            1 => array('o.pay_status' => '1', 'o.ship_status' => '1', 'o.received_status' => '0', 'o.status' => 'active', 'o.local_id' => session('userInfo.local_id')),// 已发货
            2 => array('o.pay_status' => '1', 'o.ship_status' => '1', 'o.received_status' => '1', 'o.status' => 'active', 'o.local_id' => session('userInfo.local_id')), //已收货  部分发货，不能确认收货 提示货没发完，收货定时任务，判断 发货状态是 1
            3 => array('o.pay_status' => '0', 'o.status' => 'active', 'o.local_id' => session('userInfo.local_id')),//待支付
            4 => array( 'o.status' =>['in','dead,allrefund'], 'o.local_id' => session('userInfo.local_id')),//已经作废【未支付订单超时】，定时返回库存
            5 => array('o.status' => 'finish', 'o.local_id' => session('userInfo.local_id')),//已完成
            //6=>array('o.pay_status'=>'1','o.is_zt'=>1,'o.status'=>'active','o.local_id'=>session('userInfo.local_id')),//店铺自提  [完成按钮]  状态 finish 库存操作
            6 => array('o.local_id' => session('userInfo.local_id')),
        );



        if($_GET['select_type'] == 'createtime'){
            $b_time = strtotime($_GET['begin_time']);
            $end_time = strtotime($_GET['end_time']);
            $where[] = 'o.'.$_GET['select_type'] . " > ".$b_time .' and '. 'o.'.$_GET['select_type']. " < ".$end_time;
        }
        if (!empty($_GET['search_val']) && $_GET['select_type'] != 'createtime') {
            $where[] = 'o.'.$_GET['select_type'] . " like '%" . $_GET['search_val'] . "%'";
        }

        $where[] = $sub[$view];

        $orderList = $this->alias('o')->field("o.*,m.nickname")
            ->join("left join " . C('DB_PREFIX') . "b2c_members m on o.member_id = m.member_id")
            ->where($where)
            ->page($p . ",15")->order('o.createtime desc')->select();


        $count = $this->alias('o')->where($where)->count();// 查询满足要求的总记录数


        $Page = new \Think\Page($count, 15,$_GET);// 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page->show();// 分页显示输出


        foreach ($orderList as $k => $item) {




            $orderList[$k]['time'] = date('Y-m-d H:i:s', $item['createtime']);
            $orderList[$k]['detailurl'] = U("orders/orderDetail/", ['id' => $item['order_id']]);;
            $orderList[$k]['pay_status'] = $item['pay_status'] == 1 ? '已支付' : '未支付';
            $orderList[$k]['ship_status'] = $item['ship_status'] == 1 ? '已发货' : '未发货';
            if ($item['ship_status'] == 2) {
                $orderList[$k]['ship_status'] = "部分发货";
            }


            if($item['refund_ago_money_status']=='1' && I('get.view',0,intval())>0){
                $orderList[$k]['sell_later'] = "售后退款";
            }elseif ($item['refund_ago_goods_status']=='1' && I('get.view',0,intval())>0){
                $orderList[$k]['sell_later'] = "退款退货";
            }

            $orderList[$k]['is_zt'] = $item['is_zt'] == 1 ? '<span style="color: #ff2e49">自提订单</span>' : '普通订单';
            //订单备注最新信息
            if (!empty($item['mark_text'])) {
                $mark = unserialize($item['mark_text']);
                $markContent = end($mark);
                $orderList[$k]['mark'] = $markContent['mark_text'];
            }

            if ( $item['refund_front_status'] == '1') {
                $orderList[$k]['isback'] = "<span style='color: #ff0000'>客户申请售后</span>";
            }else{
                $orderList[$k]['isback'] = "订单正常";
            }

            // 验证状态
            if (!$this->orderIsCheckCardByItem($item['order_id'])){
                $msg = '不需验证';
            }else{
                $list = M('b2c_members')->where('member_id = '.$item['member_id'])->field(['identity_verifi'])->find();
                switch ($list['identity_verifi']){
                    case 1:
                        $msg = '验证通过';
                        break;
                    case 2:
                        $msg = '验证不过';
                        break;
                    case 3:
                        $url = U('/Qgs/Identity/index/view/3', ['id' => $item['member_id']]);
                        $msg = '<a href="'.$url.'">申请审核</a>';
                        break;
                    case 0:
                    default:
                        $msg = '未验证';
                        break;
                }
            }
            $orderList[$k]['verifyMsg'] = $msg;

            //供应商名称
            $SupplierInfo = $this->getSupplierDetail($item['order_id']);
            $orderList[$k]['supplierName'] = (empty($SupplierInfo['name']) ? '还未填写' : $SupplierInfo['name']);

            $orderList[$k]['action'] = $this->actionButton($item, $view);

        }

        $payList['page'] = $show;
        $payList['list'] = $orderList;


        if (!empty($payList)) {
            return $payList;
        } else {
            return array('msg' => '暂无订单', 'status' => 2);
        }


    }

    /**
     * 订单商品是否需要身份证验证
     * @param $order_id
     * @return bool
     */
    public function orderIsCheckCardByItem($order_id)
    {
        $isCard = M('b2c_order_items')
            ->where(['order_id'=>$order_id, 'identity_card_status' => ['in', ['1', '2']],'item_type'=>['in', ['product', 'pkg']]])
            ->count('item_id');
        if ($isCard != 0) return true;
        return false;
    }

    /**
     * @param string $order_id
     * 订单详细
     */

    public function orderDetail($order_id = '')
    {

        $orderGoods['product'] = M('b2c_order_items i')
            ->join("left join " . C('DB_PREFIX') . "b2c_orders o on o.order_id = i.order_id")
            ->join("left join " . C('DB_PREFIX') . "b2c_store_product sp on sp.product_id = i.product_id and sp.local_id = o.local_id")
            ->join("left join " . C('DB_PREFIX') . "b2c_products p on p.product_id = sp.product_id")
            ->where(['i.order_id' => $order_id, 'o.local_id' => session('userInfo.local_id')])
            ->field("o.*,i.*,p.barcode,sp.freez,sp.store,p.unit,case sp.is_identity_card when 'true' then '是' else '否' end isCard, 
            case sp.is_identity_card_photo when 'true' then '是' else '否' end isCardPhote")
            ->select();
        if (empty($orderGoods['product'])) {
            return array("msg" => "参数错误，获取商品不存在", "status" => 0);
        }


        $memberBool = false;
        foreach ($orderGoods['product'] as $k => $item) {
            $orderGoods['detail']['shipping'] = $item['shipping']; //配送方式
            $orderGoods['detail']['ship_area'] = $item['ship_area'];//收货地区
            $orderGoods['detail']['ship_addr'] = $item['ship_addr'];//收货地址
            $orderGoods['detail']['ship_time'] = $item['ship_time'];//配送时间
            $orderGoods['detail']['ship_mobile'] = $item['ship_mobile'];//收货手机
            $orderGoods['detail']['ship_name'] = $item['ship_name'];//收货人姓名
            $orderGoods['detail']['payment'] = $item['payment'];//支付方式
            $orderGoods['detail']['weight'] = $item['weight'];//订单总重量
            $orderGoods['detail']['memo'] = $item['memo'];//客户附言
            $orderGoods['detail']['cost_freight'] = $item['cost_freight'];//配送费用
            $orderGoods['detail']['payed'] = $item['payed'];//订单支付金额
            $orderGoods['detail']['total_amount'] = $item['total_amount'];//订单总额
            $orderGoods['detail']['cost_item'] = $item['cost_item'];//商品总额
            $orderGoods['detail']['pmt_order'] = $item['pmt_order'];//优惠抵扣金额
            $orderGoods['detail']['order_id'] = $item['order_id'];//订单ID
            $orderGoods['detail']['ship_status'] = $item['ship_status'];//发货状态
            $orderGoods['detail']['createtime'] = date('Y-m-d H:i:s', $item['createtime']);//下单时间
            $orderGoods['detail']['shipping_id'] = $item['shipping_id'];//配送方式ID
            $orderGoods['detail']['ship_zip'] = $item['ship_zip'];//收货人邮编
            $orderGoods['printing']['local_name'] = $item['local_name'];//店铺名称
            $orderGoods['printing']['shipping'] = $item['shipping'];//配送方式
            $orderGoods['detail']['order_id'] = $item['order_id'];//订单ID
            $orderGoods['detail']['member_id'] = $item['member_id'];//订单ID
            $orderGoods['detail']['is_zt'] = $item['is_zt'];//订单ID
            $orderGoods['detail']['zT_addr'] = $item['zT_addr'];//自提地址
            $orderGoods['detail']['pickedup_bn'] = $item['pickedup_bn'];//自提电话
            $orderGoods['detail']['ship_status'] = $item['ship_status'];//发货状态
            $orderGoods['detail']['refund_front_status'] = $item['refund_front_status'];//发货状态
            $orderGoods['detail']['youhui'] = $item['cost_item'] - $item['total_amount'];//优惠金额
            $orderGoods['detail']['pay_status'] = $item['pay_status'];//是否支付
            $orderGoods['detail']['ship_status'] = $item['ship_status'];//是否发货
            $orderGoods['detail']['status'] = $item['status'];//订单状态

            if($item['pay_status'] == '1'){
                $orderGoods['detail']['is_zhifu'] = '已支付';//支付状态
            }else{
                $orderGoods['detail']['is_zhifu'] = '未支付';//支付状态
            }


            if (!empty($item['ship_area'])) {
                $add = str_replace("mainland:", "", $item['ship_area']);
                $pos = strpos($add, ':');
                if (!empty($pos)) {
                    $orderGoods['detail']['ship_area'] = substr($add, 0, $pos);
                }
            }
            $specVal = '';
            if (!empty($item['addon'])) {
                $spec = unserialize($item['addon']);
                if (empty($spec['product_attr'])) {
                    $specVal = "(" . $item['addon'] . ")";
                } else {
                    $specVal .= "(";
                    foreach ($spec['product_attr'] as $k1 => $val) {
                        $specVal .= $val['label'] . ":" . $val['value'];
                    }
                    $specVal .= ")";

                }
                $sc = '';
                if (!empty($specVal)) {
                    $sc = str_replace("(", "", $specVal);
                    $sc = str_replace(")", "", $sc);
                }
                $orderGoods['product'][$k]['spec_info'] = $sc;
                $orderGoods['product'][$k]['name'] = $item['name'] . $specVal;
                $orderGoods['product'][$k]['needsend'] = $item['nums'] - $item['sendnum'];

            } else {
                $orderGoods['product'][$k]['name'] = $item['name'];
                $orderGoods['product'][$k]['needsend'] = $item['nums'] - $item['sendnum'];
            }

            //会员资料验证
            if (!$memberBool  and !empty($item['member_id']) and $item['isCard'] == '是'){
                $info = M('b2c_members')
                    ->where(['member_id' => $item['member_id']])
                    ->field(['identity_name', 'identity_card_num', 'identity_verifi', 'identity_photo', 'identity_photo_1'])
                    ->find();
                $orderGoods['identity']['name'] = (empty($info['identity_name']) ? '无' : $info['identity_name']);
                $orderGoods['identity']['card_num'] = (empty($info['identity_card_num']) ? '无'  : $info['identity_card_num']);
                switch ($info['identity_verifi']){
                    case 0 :
                        $status = '<span id="status" style="color: #ff0000;">未验证</span>';
                        break;
                    case 1 :
                        $status = '<span id="status">验证通过</span>';
                        break;
                    case 2 :
                        $status = '<span id="status" style="color: #ff0000;">验证未通过</span>';
                        break;
                    case 3 :
                        $url = U('/Qgs/Identity/index/view/3', ['id' => $item['member_id']]);
                        $status = '<span id="status" style="color: #ff0000;"><a href="'.$url.'">申请审核</a></span>';
                        break;
                    default:
                        $status = '';
                        break;
                }
                $orderGoods['identity']['status'] = $status;
                $orderGoods['identity']['photo'] = (empty($info['identity_photo']) ? '无' : '有');
                $orderGoods['identity']['photo1'] = (empty($info['identity_photo_1']) ? '无' : '有');
                $memberBool = true;
            }
        }

        return $orderGoods;

    }

    /**
     * 获取供应商详细消息
     * @param string $order_id
     * @return mixed
     */
    public function getSupplierDetail($order_id = '')
    {
        $supplierDetail = M('qgs_supplier s')
            ->join("left join " . C('DB_PREFIX') . "b2c_orders o on o.supplier_id = s.supplier_id")
            ->where(['o.order_id' => $order_id, 'o.local_id' => session('userInfo.local_id')])
            ->field('s.supplier_id, s.code, s.name, s.full_name, s.phone')
            ->find();
        return $supplierDetail;
    }

    /**
     * @param string $order
     * @param $view
     * @return mixed
     *
     */
    public function actionButton($order = '', $view)
    {

        $url = U("orders/orderDetail/", ['id' => $order['order_id'],'view' => $view]);
        $urlMark = U("orders/orderMark/", ['id' => $order['order_id']]);
        $urlDeli = U("orders/orderDelivery/", ['id' => $order['order_id']]);
        //print_r($order);
        /*$finishBut = "isSure($order)";
        $ztBut = "isZtSure($order)";*/
        //判断是否申请退货退款置灰按钮操作
        //$is_refund = M('b2c_refund_money')->where(['order_id'=>$order,'local_id'=>session('userInfo.local_id'),'type'=>'1','status'=>['neq','0']])->find();
        /*$is_refund = M('b2c_refund_money_goods mg')
           ->join("left join ".C('DB_PREFIX')."b2c_refund_money m on m.id = mg.refund_money_id")
           ->where(['m.order_id'=>$order['order_id'],'m.local_id'=>session('userInfo.local_id'),'m.type'=>'1','m.status'=>['neq','0']])
           ->field("sum(mg.num) as total_num")
           ->find();*/



        if ( $order['refund_front_status'] == '1') {
            $butt = "<div class='edit-list'><ul class='order-edit'>
	                <li><a href='/Qgs/Refund/index/view/1.html' style='color: #ff0000' >客户退款</a></li>
	                <li class='cur'><a href='" . $url . "'>查看订单</a></li>
	                <li><a href='" . $urlMark . "'>订单备注</a></li>
                </ul>
                </div>";
        } else {
            $butt = "<div class='edit-list'><ul class='order-edit'>
	                <li><a href='#' class='suggest' data-id='$urlDeli' >发货</a></li>
	                <li class='cur'><a href='" . $url . "'>查看订单</a></li>
	                <li><a href='" . $urlMark . "'>订单备注</a></li>
                </ul>
                </div>";
        }


        if($order['is_zt']==1){

            //申请售后，可以确认收货
            $butt_delivery = "<div class='edit-list'><ul class='order-edit'>
                      <li><a href='" . $url . "' >查看订单</a></li>                                        
                        <li><a href='" . $urlMark . "'>订单备注</a></li>
                          <li><a href='javascript:isSureGet(".$order['order_id'].");'>确认收货</a></li>
                      </ul>
                </div>";
        }else{
            $butt_delivery = "<div class='edit-list'><ul class='order-edit'>
                      <li><a href='" . $url . "' >查看订单</a></li>
                        <li><a href='" . $urlMark . "'>订单备注</a></li>
                      </ul>
                </div>";
        }

        $action = array(
            /*0=>"<a href='#' >发货</a><a href='".$url."'>查看订单</a><a href='#'>订单备注</a>",*/
            0 => $butt,
            1 => $butt_delivery,
            /*<li class='cur'><a href='javascript:void(0);' onclick='".$finishBut."'>完成</a></li>*/
            2 => "<div class='edit-list'><ul class='order-edit'>
                      <li><a href='" . $url . "' >查看订单</a></li>                                              
                         <li><a href='" . $urlMark . "'>订单备注</a></li>
                      </ul>
                </div>",
            3 => "<div class='edit-list'><ul class='order-edit'>
                      <li  class='cur'><a href='" . $url . "' >查看订单</a></li>
                      <li><a href='" . $urlMark . "'>订单备注</a></li>
                      </ul>
                </div>",
            4 => "<div class='edit-list'><ul class='order-edit'>
                      <li  class='cur'><a href='" . $url . "' >查看订单</a></li>
                    </ul>
                </div>",
            5 => "<div class='edit-list'><ul class='order-edit'>
                      <li  class='cur'><a href='" . $url . "' >查看订单</a></li>
                      <li><a href='" . $urlMark . "'>订单备注</a></li>
                      </ul>
                </div>",
            /*   6=>"<div class='edit-list'><ul class='order-edit'>
                         <li  class='cur'><a href='".$url."' >查看订单</a></li>
                          <li class='cur'><a href='javascript:void(0);' onclick='".$ztBut."'>完成</a></li>

                         </ul>
                   </div>",*/
            6 => "<div class='edit-list'><ul class='order-edit'>
                      <li  class='cur'><a href='" . $url . "' >查看订单</a></li></ul></div>",
        );

        return $action[$view];

    }

    public function saveMark($order_id, $text)
    {


        if (empty($text)) {
            return array('msg' => '内容不能为空', 'status' => 0);
        }
        $arr = array('0' => [
            'mark_text' => $text,
            'add_time' => time(),
            'op_name' => session('userInfo.username'),
        ]

        );

        $recontent = "<tr><td>" . $arr[0]['op_name'] . "</td><td>" . $arr[0]['mark_text'] . "</td><td>" . date('Y-m-d H:i:s', $arr[0]['add_time']) . "</td></tr>";


        $oldArr = $this->markList($order_id);

        if (!empty($oldArr)) {
            $newArr = array_merge($oldArr, $arr);
            $val = serialize($newArr);
        } else {
            $val = serialize($arr);
        }


        $result = $this->where(['order_id' => $order_id, 'local_id' => session('userInfo.local_id')])->save(['mark_text' => $val]);

        if ($result) {
            return array('msg' => '保存成功', 'status' => 1, 'content' => $recontent);
        } else {
            return array('msg' => '保存失败', 'status' => 0);
        }

    }

    /**
     * 备注内容list
     */
    public function markList($order_id = '')
    {

        $mark = $this->where(['order_id' => $order_id, 'local_id' => session('userInfo.local_id')])->field('mark_text')->find();

        if (!empty($mark)) {
            $markArr = unserialize($mark['mark_text']);
            foreach ($markArr as $k => $item) {
                $markArr[$k]['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
            }

        }

        return $markArr;
    }

    /**
     * 订单日志
     */
    public function ordreLog($order_id = '')
    {

        $Log = M('b2c_order_log olog')
            ->join("left join " . C('DB_PREFIX') . "b2c_orders o on o.order_id = olog.rel_id")
            ->where(['olog.rel_id' => $order_id, 'o.local_id' => session('userInfo.local_id')])->select();

        if (empty($Log)) {
            return array('msg' => '参数错误', 'status' => 0);
        }
        foreach ($Log as $k => $item) {
            $Log[$k]['time'] = date('Y-m-d H:i:s', $item['alttime']);

            if ($item['result'] == 'SUCCESS') {
                $Log[$k]['result'] = '成功';
            } else {
                $Log[$k]['result'] = '失败';
            }

            switch ($item['behavior']) {
                case 'creates':
                    $Log[$k]['behavior'] = "创建";
                    if ($arr_log_text = unserialize($item['log_text'])) {
                        $item['log_text'] = '';
                        foreach ($arr_log_text as $arr_log) {
                            $Log[$k]['log_text'] .= $arr_log['txt_key'];
                        }
                    }


                    break;
                case 'updates':
                    $Log[$k]['behavior'] = "修改";
                    if ($arr_log_text = unserialize($item['log_text'])) {
                        $Log[$k]['log_text'] = '';
                        foreach ($arr_log_text as $arr_log) {
                            $Log[$k]['log_text'] .= $arr_log['txt_key'];
                        }
                    }
                    break;
                case 'payments':
                    $Log[$k]['behavior'] = "支付";
                    if ($arr_log_text = unserialize($item['log_text'])) {
                        $Log[$k]['log_text'] = '';
                        foreach ($arr_log_text as $arr_log) {
                            // $Log[$k]['log_text'] .= $arr_log['txt_key'],$arr_log['data'][0],$arr_log['data'][1],$arr_log['data'][2];
                        }
                    }
                    break;
                case 'refunds':
                    $Log[$k]['behavior'] = "售后";
                    if ($arr_log_text = unserialize($item['log_text'])) {
                        $Log[$k]['log_text'] = '';
                        foreach ($arr_log_text as $arr_log) {
                            $Log[$k]['log_text'] .= $arr_log['txt_key'];
                        }
                    }
                    break;
                case 'delivery':
                    $Log[$k]['behavior'] = "发货";
                    if ($arr_log_text = unserialize($item['log_text'])) {
                        $Log[$k]['log_text'] = '';
                        foreach ($arr_log_text as $arr_log) {
                            //  $Log[$k]['log_text'] .= $arr_log['txt_key'],$arr_log['data'][0],$arr_log['data'][1],$arr_log['data'][2],$arr_log['data'][3],$arr_log_text['data'][4],$arr_log['data'][5];
                        }
                    }
                    break;
                case 'member_refund':
                    $Log[$k]['behavior'] = "用户申请退款";
                    break;
                case 'member_refund_goods':
                    $Log[$k]['behavior'] = "用户申请退货退款";
                    break;

                case 'refund_fail':
                    $Log[$k]['behavior'] = "用户申请售后";
                    break;
                case 'received_status':
                    $Log[$k]['behavior'] = "后台自提确认收货";
                    break;
                case 'receive':
                    $Log[$k]['behavior'] = "用户确认收货";
                    break;
                case 'delete':
                    $Log[$k]['behavior'] = "用户删除订单";
                    break;
                case 'reship':
                    $Log[$k]['behavior'] = "退货";
                    if ($arr_log_text = unserialize($item['log_text'])) {
                        $Log[$k]['log_text'] = '';
                        foreach ($arr_log_text as $arr_log) {
                            // $Log[$k]['log_text'] .= $arr_log['txt_key'],$arr_log['data'][0],$arr_log['data'][1],$arr_log['data'][2],$arr_log['data'][3],$arr_log_text['data'][4],$arr_log['data'][5];
                        }
                    }
                    break;
                case 'finish':
                    $Log[$k]['behavior'] = "完成";
                    if ($arr_log_text = unserialize($item['log_text'])) {
                        $Log[$k]['log_text'] = '';
                        foreach ($arr_log_text as $arr_log) {
                            $Log[$k]['log_text'] .= $arr_log['txt_key'];
                        }
                    }
                    break;
                case 'cancel':
                    $Log[$k]['behavior'] = "取消";
                    break;
                default:
                    break;
            }
        }

        return $Log;

    }

    /**
     * 发货订单操作日志
     */
    public function addOrderLog($delivery_id, $orderGoods)
    {

        $delivery_log = array(
            'rel_id' => $delivery_id['order_id'],
            'op_id' => session('userInfo.local_id'),
            'op_name' => session('userInfo.username'),
            'alttime' => time(),
            'bill_type' => 'order',
            'behavior' => 'delivery',
            'result' => 'SUCCESS',

        );
        //是否是部分发货


        $content = '';
        foreach ($orderGoods['product'] as $k => $item) {
            if ($item['nums'] - $delivery_id['send'][$item['item_id']] > 0) {
                $content .= "<br>部分发货商品：" . $item['name'] . "数量：" . $delivery_id['send'][$item['item_id']];
            } else {
                $content .= "<br>发货商品：" . $item['name'] . "数量：" . $delivery_id['send'][$item['item_id']];
            }

        }

        // item_id

        $dlytype = M('b2c_dlytype')->where(['dt_id' => $delivery_id['delivery']])->field('dt_name')->find();

        $dlycorp = M('b2c_dlycorp')->where(['corp_id' => $delivery_id['logi_id']])->field('name')->find();
        if (!empty($delivery_id['logi_no'])) {
            $logi_no = ",物流单号:" . $delivery_id['logi_no'];
        }
        $delivery_log['log_text'] = "发货完成，配送方式:" . $dlytype['dt_name'] . ",物流公司：" . $dlycorp['name'] . $logi_no . "，物流费用:" . $delivery_id['money'] . $content;


        $result = M('b2c_order_log')->data($delivery_log)->add();

        return $result;


    }


    /**
     * 发货详情
     */

    public function ordreDe($order_id = '')
    {

        $orderGoods = $this->orderDetail($order_id);

        //查找配送方式
        $dlytype = M('b2c_dlytype')->field('dt_id,dt_name')->select();

        $dlyOrdertype = M('b2c_orders o')
            ->join("left join " . C('DB_PREFIX') . "b2c_dlytype dt on dt.dt_id = o.isStore_delivery")
            ->where(['o.order_id' => $order_id])
            ->field("dt.dt_name,dt.dt_id")
            ->find();


        $orderGoods['Select_dt'] = $dlyOrdertype;
        //print_r($dlyOrdertype);exit;
        $orderGoods['dlytype'] = $dlytype;
        //查找物流公司
        $dlycorp = M('b2c_store_dlycorp')->where(['local_id'=>session('userInfo.local_id')])->field('corp_id,name')->select();
        $orderGoods['dlycorp'] = $dlycorp;

        //查询配送方式对应的 物流公司

        /* $dly =  M('b2c_dlytype dt')
             ->join("left join ".C('DB_PREFIX')."b2c_dlycorp dc on dt.corp_id = dc.corp_id")
             ->where(['dt.dt_id'=>$orderGoods['detail']['shipping_id']])
             ->field("dc.corp_id")
             ->find();

         $orderGoods['se_corp_id'] = $dly['corp_id'];*/
        return $orderGoods;

    }

    /**
     * 生成发货单号
     */
    public function gen_id()
    {
        $sign = '1' . date("Ymd");

        while (true) {
            list($usec, $sec) = explode(" ", microtime());
            $microtime = (float)$usec + (float)$sec;
            mt_srand($microtime);
            $randval = substr(mt_rand(), 0, -3) . rand(100, 999);

            $strList = $sign . $randval;

            $aRet = M('b2c_delivery')->where(['delivery_id' => $strList])->count();

            if (!$aRet) {
                break;
            }
        }
        return $sign . $randval;

    }

    /**
     * @param $deli 发货数据
     * @param $delivery_id  发货单号
     */
    public function createDelivery($deli, $delivery_id)
    {

        $member_id = $this->where(['order_id' => $deli['order_id'], 'local_id' => session('userInfo.local_id')])
            ->field("member_id")
            ->find();

        $corp_name = M('b2c_dlycorp')->where(['corp_id' => $deli['logi_id']])
            ->field("name")
            ->find();

        $delivery_bill = array(
            'delivery_id' => $delivery_id,
            'order_id' => $deli['order_id'],
            'member_id' => $member_id['member_id'],
            'money' => $deli['money'],
            'delivery' => $deli['delivery'],
            'logi_id' => $deli['logi_id'],
            'logi_name' => $corp_name['name'],
            'logi_no' => $deli['logi_no'],
            'ship_name' => $deli['ship_name'],
            'ship_area' => $deli['ship_area'],
            'ship_addr' => $deli['ship_addr'],
            'ship_zip' => $deli['ship_zip'],
            'ship_mobile' => $deli['ship_mobile'],
            't_begin' => time(),
            'op_name' => session('userInfo.username'),
            'local_id' => session('userInfo.local_id'),
            'status' => 'succ',

        );

        if (empty($deli['ship_addr'])) {
            return array('msg' => '请填写收货地址', 'status' => 0);
        }

        if (empty($deli['ship_mobile'])) {
            return array('msg' => '手机号码不能为空', 'status' => 0);
        }
        if (empty($deli['ship_name'])) {
            return array('msg' => '请填写收货人姓名', 'status' => 0);
        }


        if ($deli['logi_id'] == 0 && $deli['delivery']==2 ) {

            return array('msg' => '请选择物流公司', 'status' => 0);
        }
        if ( $deli['delivery']==2  && empty($deli['logi_no']) ) {

            return array('msg' => '请填写物流单号', 'status' => 0);
        }


        $result = M('b2c_delivery')->data($delivery_bill)->add();

        if ($result ===false) {
            return array('msg' => '发货失败', 'status' => 0);
        }else{
            return array('msg' => '成功', 'status' => 1);
        }


    }

    /**
     * 发货单详情
     */
    public function createDeItems($deli, $delivery_id, $orderGoods)
    {

        $start_status = true;
        foreach ($orderGoods['product'] as $k => $item) {
            $deli_item[$k]['delivery_id'] = $delivery_id;
            $deli_item[$k]['order_item_id'] = $item['item_id'];
            $deli_item[$k]['item_type'] = 'goods';
            $deli_item[$k]['product_id'] = $item['product_id'];
            $deli_item[$k]['product_bn'] = $item['bn'];
            $deli_item[$k]['product_name'] = $item['name'];
            $deli_item[$k]['number'] = $deli['send'][$item['item_id']];
            if(empty( $deli['send'][$item['item_id']])){
                continue;
            }

            $result = M('b2c_delivery_items')->data($deli_item[$k])->add();
            if (!$result) {
                $start_status = false;
                break;
            }
        }
        return $start_status;
    }

    /**
     *发货订单详情【货品明细】
     *
     */
    public function createOrderDeli($arrDelivery, $delivery_id, $orderGoods)
    {


        $items = serialize($orderGoods['product']);
        $de_product = array(
            'order_id' => $arrDelivery['order_id'],
            'dlytype' => 'delivery',
            'dly_id' => $delivery_id,
            'items' => $items,
        );
        $result = M('b2c_order_delivery')->data($de_product)->add();

        if ($result) {
            return array('msg' => '添加订单详情【货品明细】成功', 'status' => 1);
        } else {
            return array('msg' => '添加订单详情【货品明细】失败', 'status' => 0);
        }

    }


    /**
     * 更新order_items
     */
    public function orderItems($item_id, $orderGoods)
    {

        foreach ($item_id['send'] as $k => $item) {
            $arrItem[$k]['item_id'] = $k;
            $arrItem[$k]['sendnum'] = $item;
            $result = M('b2c_order_items')->where(['item_id' => $k])->setInc('sendnum', $item);
        }

        //  $orderGoods = $this->orderDetail($item_id['order_id']);
        $sendnum = 0;
        $buynum = 0;
        foreach ($orderGoods['product'] as $k => $item) {
            $sendnum += $item['sendnum'];
            $buynum += $item['nums'];
        }
        //查询订单详情，发货量< 购买量  ship_status=2   发货量 = 购买量 1  ship_status=2
        if ($sendnum < $buynum) {
            $is_ok = $this->where(['order_id' => $item_id['order_id'], 'local_id' => session('userInfo.local_id')])->save(['ship_status' => '2']);
        } elseif ($sendnum == $buynum) {
            $is_ok = $this->where(['order_id' => $item_id['order_id'], 'local_id' => session('userInfo.local_id')])->save(['ship_status' => '1']);
        }

        return $is_ok;

    }


    /**
     * 库存更改
     */
    public function storeChange($order, $orderGoods)
    {
        $is_Ok = true;

        foreach ($orderGoods['product'] as $k => $item) {
            //更新店铺商品表
            //判断库存是否足够
            $store_product = M('b2c_store_product')->where(['product_id' => $item['product_id'], 'local_id' => session('userInfo.local_id')])->field('store,freez')->find();

            if ($store_product['freez'] < $order['send'][$item['item_id']] || $store_product['store'] < $order['send'][$item['item_id']]) {
                $is_Ok = false;

                return array('msg' => '库存不足', 'status' => 0);
                break;
            }


            $is_Ok_store = M('b2c_store_product')->where(['product_id' => $item['product_id'], 'local_id' => session('userInfo.local_id')])
                ->setDec('store', $order['send'][$item['item_id']]);
            $is_Ok_store = M('b2c_store_product')->where(['product_id' => $item['product_id'], 'local_id' => session('userInfo.local_id')])
                ->setDec('freez', $order['send'][$item['item_id']]);
        }

        return array('msg' => '成功', 'status' => 1);


    }





}